/**
 * 缓存时间(秒)
 */  //20;
const cacheTime = 5 * 60;

const LOCAL_STORAGE_KEY = 'BDC_ACCEPTED_INTERVAL_ID_ARR';

/**
 * 更新前端间隔时间(秒)
 * @type {number}
 */
const updateTime = 1;

//缓存数据
var accptedCache = {
  //缓存时间
  time: '',
  //各区县基础数量
  countArr: [],
  //各区县每秒增加量(没有增加数组为空)
  addArr: []
};
/**
 * 最新各区县数量 在五分钟后复制为基础数量
 */
var newAccptedCache = {
  time: '',
  countArr: [],
  addArr: []
}


/**
 * 获取区县增量
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/18 15:35
 **/
const getQxAddCount = (name) => {
  for (let i = 0; i < accptedCache.addArr.length; i++) {
    if (accptedCache.addArr[i].name === name) {
      return accptedCache.addArr[i].value;
    }
  }
  return 0;
}

/**
 * 计算增量并且保存到缓存
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/18 15:03
 **/
const calculateAddCount = (newArr, oldArr) => {
  accptedCache.addArr = [];
  for (let i = 0; i < newArr.length; i++) {
    let newQxObj = newArr[i];
    let oldQxObj = oldArr[i];
    let addObject = {};
    addObject.name = newQxObj.qxName;
    if (!!newQxObj.qxName) {
      addObject.value = (newQxObj.qxCount - oldQxObj.qxCount) / (cacheTime * 1.0);
      if (addObject.value < 0) {
        addObject.value = 0;
      }
    } else {
      addObject.value = 0;
    }
    accptedCache.addArr.push(addObject);
  }
}
/**
 * 判断是否跨天
 * @returns {boolean}
 */
const isSameDay = () => {
  let newCacheDate = newAccptedCache.time;
  let oldCacheDate = accptedCache.time;
  return (oldCacheDate.getFullYear() === newCacheDate.getFullYear()
    && oldCacheDate.getMonth() === newCacheDate.getMonth()
    && oldCacheDate.getDay() === newCacheDate.getDay());
}
/**
 * 清除所有定时器
 */
const clearAllInterval = () => {
  let intervalId = localStorage.getItem(LOCAL_STORAGE_KEY);
  clearTimeout(parseInt(intervalId));
  localStorage.setItem(LOCAL_STORAGE_KEY, '');
  console.log(`清理定时器时间${new Date()}`, 'bdcCount-log')
}
/**
 * 创建页面更新不动产数量的定时器
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/18 14:56
 **/
const createInterval = (pageVueObject) => {
  //计算前时间 当作本次请求数据的时间
  let uuid = Math.random();
  //每秒钟更新区县数据量
  let intervalId = 0;
  let maxSum = getCountSum(newAccptedCache.countArr);
  intervalId = setInterval(() => {
    // console.log(`执行任务id:${uuid}`, 'bdcCount-log')
    // console.log(`执行时间${new Date()}`, 'bdcCount-log')
    let sum = 0;
    let resArr = [];
    //缓存数据和当前时间的相差(秒)
    let nowtime = (new Date()).getTime();
    let addtime = parseInt((nowtime - (accptedCache.time).getTime()) / 1000);
    for (let i = 0; i < accptedCache.countArr.length; i++) {
      let qxres = {};
      let qxCache = accptedCache.countArr[i];
      let addCount = getQxAddCount(qxCache.qxName);
      qxres.QXMC = qxCache.qxName;
      qxres.NCOUNT = parseInt(parseInt(qxCache.qxCount) + addCount * addtime)
      sum += qxres.NCOUNT;
      resArr.push(qxres);
    }
    //不能超过最后总量  定时器执行5分钟
    if (sum > maxSum || addtime >= cacheTime) {
      clearAllInterval();
      //5分钟后再次请求接口
      getQXAcceptedCount(pageVueObject);
    } else {
      pageVueObject.bldData = resArr.sort((a, b) => {
        return b.NCOUNT - a.NCOUNT
      })
      pageVueObject.toOrderNum(sum);
    }
  }, updateTime * 1000);
  localStorage.setItem(LOCAL_STORAGE_KEY, intervalId);
}

const setCountRequestInterval = (pageVueObject) => {
  setTimeout(() => {
    getQXAcceptedCount(pageVueObject);
  }, 1000 * cacheTime + updateTime);
}

/**
 * 清理缓存
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/22 14:30
 **/
const clearAccptedCache = () => {
  accptedCache = {
    //缓存时间
    time: '',
    //各区县基础数量
    countArr: [],
    //各区县每秒增加量(没有增加数组为空)
    addArr: []
  };
}
/**
 * 结果过滤
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/22 11:24
 **/
const resaultFilter = (res) => {
  let qxCountResArr = [];
  if (!!res) {
    for (var i in res) {
      let qxObj = res[i][0]
      if (qxObj.QXMC === '中心城区') {
        qxObj.QXMC = '市本级'
      }
      if (qxObj.QXMC === '简阳市') {
        qxObj.QXMC = '简阳市(含东部新区)'
      }
      let count = parseInt(qxObj.NCOUNT);
      if (!count) {
        count = 0;
      }
      let qxCount = {}
      qxCount.qxName = qxObj.QXMC;
      qxCount.qxCount = count;
      qxCountResArr.push(qxCount);
    }
  }
  return qxCountResArr;
  // return qxCountResArr.sort((p) => {
  //   p.NCOUNT
  // });
}

const dateHandle = (pageVueObject, res) => {
  if (!res || Object.keys(res).length < 0) {
    //空数据   不定时更新 等待下五分钟数据
    setCountRequestInterval(pageVueObject);
    return true;
  }
  let oldDatas = resaultFilter(res.oldDatas);
  let newDatas = resaultFilter(res.newDatas);
  if (oldDatas == null
    || newDatas == null
    || oldDatas.length < 0
    || newDatas.length < 0) {
    //空数据   不定时更新 等待下五分钟数据
    setCountRequestInterval(pageVueObject);
    return true;
  } else if (getCountSum(newDatas) === getCountSum(newAccptedCache.countArr)) {
    //数据和上次请求一样  不定时更新 等待下五分钟数据
    setCountRequestInterval(pageVueObject);
    return true;
  } else {
    // if (isSameDay()) {
    newAccptedCache.countArr = newDatas;
    accptedCache.countArr = oldDatas;
    accptedCache.time = new Date();
    //预计5分钟后涨到指定数量
    newAccptedCache.time = new Date((new Date()).getTime() - cacheTime * 1000);
    // } else {
    //   newAccptedCache.countArr = newDatas;
    //   newAccptedCache.time = new Date();
    //   accptedCache.time = new Date()
    //   accptedCache.countArr = newDatas
    // }
    return false;
  }

}

const getCountSum = (arr) => {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += parseInt(arr[i].qxCount)
  }
  return sum;
}

/**
 * 处理请求结果
 *  做缓存、算每秒增量
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/18 14:51
 **/
const qxAcceptedCountHandle = (pageVueObject, res) => {
  clearAllInterval();
  //结果过滤 处理数据
  if (dateHandle(pageVueObject, res)) {
    return;
  }
  //计算增量
  calculateAddCount(newAccptedCache.countArr, accptedCache.countArr)
  //创建计时器
  createInterval(pageVueObject)
}
/**
 * 请求区县受理数量
 * @param null
 * @return
 * @author CYH
 * @date 2021/9/18 14:18
 **/
const getQXAcceptedCount = (pageVueObject) => {
  console.log(`开始请求不动产受理数据${new Date()}`, 'bdcCount-log')
  pageVueObject.$.ajax({
    url: pageVueObject.$API.ajaxPath,
    type: "post",
    data: {
      interfaceName: pageVueObject.interfaceName,
      methodName: "bdcslWithRegions",
      args: [localStorage.getItem("USER_ID")],
    },
    dataType: "json",
    success: (response) => {
      if (response.status === "0") {
        qxAcceptedCountHandle(pageVueObject, JSON.parse(response.result))
      }
    },
    error: (xhr) => {
      console.log(`请求不动产受理数据异常:${xhr}`, 'bdcCount-log')
      setCountRequestInterval(pageVueObject);
    },
  });

  //30秒更新一次 临时
  // clearAllInterval();
  // let intervalIdArr = [];
  // pageVueObject.$.ajax({
  //   url: pageVueObject.$API.ajaxPath,
  //   type: "post",
  //   data: {
  //     interfaceName: pageVueObject.interfaceName,
  //     methodName: "bdcslRegions",
  //     args: [localStorage.getItem("USER_ID")],
  //   },
  //   dataType: "json",
  //   success: (response) => {
  //     if (response.status === "0") {
  //       let countArr = resaultFilter(JSON.parse(response.result));
  //       let sum = 0;
  //       let resArr = [];
  //       for (let i = 0; i < countArr.length; i++) {
  //         let qxres = {};
  //         let qxCache = countArr[i];
  //         qxres.QXMC = qxCache.qxName;
  //         qxres.NCOUNT = parseInt(qxCache.qxCount);
  //         sum += qxres.NCOUNT;
  //         resArr.push(qxres);
  //       }
  //       pageVueObject.bldData = resArr;
  //       pageVueObject.toOrderNum(sum);
  //     }
  //     intervalIdArr.push(setTimeout(() => {
  //       getQXAcceptedCount(pageVueObject);
  //     }, 1000 * 30 + updateTime));
  //     localStorage.setItem(LOCAL_STORAGE_KEY, intervalIdArr.join(','));
  //   },
  //   error: (xhr) => {
  //     console.log(`请求不动产受理数据异常:${xhr}`, 'bdcCount-log')
  //     intervalIdArr.push(setTimeout(() => {
  //       getQXAcceptedCount(pageVueObject);
  //     }, 1000 * 30 + updateTime));
  //     localStorage.setItem(LOCAL_STORAGE_KEY, intervalIdArr.join(','));
  //   },
  // });


}

export default {
  getQXAcceptedCount


}
